package org.example.ims.Controller.Base;


import org.example.ims.DTO.Response;
import org.example.ims.Entity.Base.Category;
import org.example.ims.Service.Base.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/category")
public class CategoryController {
     @Autowired
     private CategoryService categoryService;

    // 根据ID查询商品类别
    @GetMapping("/{id}")
    public ResponseEntity<Response<Category>> getCategoryById(@PathVariable Integer id) {

        return categoryService.findCategoryById(id)
                .map(category -> ResponseEntity.ok(Response.success(category)))
                .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Response.<Category>error("NOT_FOUND", "Category with id " + id + " not found")));
    }

    // 查询所有类别
    @GetMapping("/search")
    public Response<Page<Category>> getAllCategory(@RequestParam(defaultValue = "0") Integer page,
                                         @RequestParam(defaultValue = "10") Integer size) {
        return Response.success(categoryService.findAllCategories(page,size));
    }

    @GetMapping
    public Response<Page<Category>> searchCategories(
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return Response.success(categoryService.searchCategories(name,page,size));
    }

    // 创建商品类别
    @PostMapping
    public ResponseEntity<Category> createCategory(@RequestBody Category category) {
        Category savedCategory = categoryService.addCategory(category);
        return ResponseEntity.ok(savedCategory);
    }

    // 更新商品类别
    @PutMapping("/{id}")
    public ResponseEntity<Category> updateUser(@PathVariable Integer id, @RequestBody Category categoryDetails) {
        Category updatedCategory=categoryService.updateCategory(id, categoryDetails);
        return ResponseEntity.ok(updatedCategory);
    }

    // 删除商品类别
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Integer id) {
        categoryService.deleteCategoryById(id);
        return ResponseEntity.ok().build();
    }
}
